package com.keepers.repair.activity

import android.content.ComponentName
import android.content.Context
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import com.keepers.repair.R
import com.keepers.repair.aidl.IMainAidlInterface
import com.keepers.repair.fragment.ChatContentFragment
import com.keepers.repair.fragment.ChatHistoryFragment
import org.jetbrains.anko.find


class ChatActivity : AppCompatActivity() {

    var service: IMainAidlInterface? = null
    private lateinit var toolbar: Toolbar
    private val connection = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName?) {}
        override fun onServiceConnected(name: ComponentName?, binder: IBinder?) {
            service = IMainAidlInterface.Stub.asInterface(binder)
            supportFragmentManager.beginTransaction()
                .add(R.id.chat_fragment, ChatContentFragment())
                .commit()
            val history = intent?.extras?.getBoolean("history")
            if (history == true) {
                supportFragmentManager.beginTransaction()
                    .replace(R.id.chat_fragment, ChatHistoryFragment())
                    .commit()
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_chat)

        title = "群聊"
        toolbar = find(R.id.chat_toolbar)

        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        toolbar.setNavigationOnClickListener {
            onBackPressed()
        }

        if (service == null) {
//            val intent = Intent(this, MainService::class.java)
            intent.action = "com.keepers.repair.service.MainService"
            bindService(intent, connection, Context.BIND_AUTO_CREATE)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unbindService(connection)
    }
}
